//
//  GYClassifyViewController.m
//  GoodLuck
//
//  Created by apple on 2018/1/26.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

static NSString *leftCellIdentifier = @"leftCellIdentifier";
static NSString *rightCellIdentifier = @"rightCellIdentifier";
static NSString *rightHeadIdentifier = @"rightHeadIdentifier";


#import "GYClassifyViewController.h"
#import "GYlargeCategory.h"
#import "GYLeftCell.h"
#import "GYLife.h"
#import "GYRightCell.h"
#import "GYRightHeadView.h"
#import "GYSearchViewController.h"
#import "GYSearchResultViewController.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYUser.h"
#import "GYSystemMessageViewController.h"
#import "GYShopingCartViewController.h"

@interface GYClassifyViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

/** 左侧表格 */
@property (nonatomic, weak) UITableView *leftTableView;

/** 左侧数据源 */
@property (nonatomic, strong) NSArray *leftLarges;


/** 右侧视图 */
@property (nonatomic, weak) UICollectionView *rightCollectionView;

/** 右侧数据源 */
@property (nonatomic, strong) NSArray *rightSources;


/** 右侧分区头的颜色 */
@property (nonatomic, strong) NSArray *colors;

/** 换粗右侧数据 */
@property (nonatomic, strong) NSMutableDictionary *cachesRightSources;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

@end

@implementation GYClassifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化UI
    [self setupUI];

    //初始化左侧视图
    [self setupLeftTableView];
    
    //初始化右边试图
    [self setupRightCollorctionView];
}

- (void)setupUI {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"arrow_left_b" tagret:self action:@selector(leftBtuClick) button:nil];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(rightBtuClick) button:nil];
    
    //设置搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, 130, 40);
    searchBar.backgroundImage = [[UIImage alloc] init];
    UITextField *searchField = [searchBar valueForKey:@"searchField"];
    searchField.layer.borderColor = RGBColor(152, 152, 152).CGColor;
    searchBar.placeholder = @"请输入关键词";
    self.navigationItem.titleView = searchBar;

}

- (void)leftBtuClick {
    NSLog(@"导航栏左侧按钮点击...");
    //显示底部工具栏
    //控制器该属性  不会走代理方法 - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item  底部工具栏需要自己设置
    self.tabBarController.selectedIndex = 0;
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)rightBtuClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    basePopoverVC.titles = @[@"首页",@"购物车",@"我的商城",@"消息"];
    basePopoverVC.images = @[@"home_w",@"ff_icon3",@"ff_icon4",@"message_w"];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                NSLog(@"首页按钮....");
                [weakSelf leftBtuClick];
            }
                break;
                
            case 1:
            {
                if ([GYUser loadUserInfo] != nil) {
                    GYShopingCartViewController *shopingCartVC = [[GYShopingCartViewController alloc] initWithNibName:@"GYShopingCartViewController" bundle:nil];
                    [weakSelf.navigationController pushViewController:shopingCartVC animated:YES];
                    
                }else {
                    weakSelf.tabBarController.selectedIndex = 2;
                }
            }
                break;
                
            case 2:
            {
                    weakSelf.tabBarController.selectedIndex = 2;
            }
                break;
                
            case 3:
            {
                if ([GYUser loadUserInfo] != nil) {
                    GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                    [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];
                    
                }else {
                    weakSelf.tabBarController.selectedIndex = 2;
                }
            }
                break;
                
            default:
                break;
        }
    };
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 64, widthScale(130, iphone6_W), 200);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];
}

//初始化左侧表格
- (void)setupLeftTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, widthScale(80, iphone6_W), ScreenHeight-64) style:UITableViewStylePlain];
    tableView.backgroundColor = RGBColor(245, 245, 245);
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    [self.view addSubview:tableView];
    self.leftTableView = tableView;
    
    //注册表格
    [tableView registerNib:[UINib nibWithNibName:@"GYLeftCell" bundle:nil] forCellReuseIdentifier:leftCellIdentifier];
    
    //初始化左侧表格的数据
    [GYlargeCategory loadLargeCategory:^(NSArray * _Nullable larges, NSError * _Nullable error) {
        if (error) {
            NSLog(@"loadLargeCategoiryFailed===%@",error);
        }else {
            self.leftLarges = larges;
            [self.leftTableView reloadData];
            
            
            GYlargeCategory *large = [self.leftLarges firstObject];
            //初始右边数据
            [self loadRightData:large.gc_id];

        }
    }];

}

//初始化右侧数据
- (void)setupRightCollorctionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.headerReferenceSize = CGSizeMake(ScreenWidth, heightScale(40, iphone6_H));
    flowLayout.itemSize = CGSizeMake((ScreenWidth-self.leftTableView.width-40)/3, 30);
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(self.leftTableView.width, 0, ScreenWidth-self.leftTableView.width, ScreenHeight-64) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsVerticalScrollIndicator = NO;
    
    [self.view addSubview:collectionView];
    self.rightCollectionView = collectionView;
    
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"GYRightCell" bundle:nil] forCellWithReuseIdentifier:rightCellIdentifier];
    
    //注册头视图
    [collectionView registerNib:[UINib nibWithNibName:@"GYRightHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:rightHeadIdentifier];

}

- (void)loadRightData:(NSString *)gc_id {
    
    //初始右边数据
    [GYLife loadLifeData:gc_id success:^(NSArray * _Nullable larges, NSError * _Nullable error) {
        if (error) {
            NSLog(@"laodRightDataFailed====%@",error);
        }else {
            //NSLog(@"larges======%@",larges);
            //1.得到数据刷新界面
            self.rightSources = larges;
            [self.rightCollectionView reloadData];
            
            //2.把数据缓存起来
            [self.cachesRightSources setObject:larges forKey:gc_id];
        }
    }];
}

#pragma mark -- <UITableViewDelegate,UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.leftLarges.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier];
//    GYlargeCategory *large = self.leftLarges[indexPath.row];
    cell.model = self.leftLarges[indexPath.row];
//    cell.signLable.text = large.gc_name;
//    cell.select = large.isSelect;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GYlargeCategory *large = self.leftLarges[indexPath.row];
    
    //1.切换右侧的数据源
    //1.1首先判断缓存中有没有数据
    NSArray *cachesSource = [self.cachesRightSources objectForKey:large.gc_id];
    if (cachesSource != nil) {
        self.rightSources = cachesSource;
        [self.rightCollectionView reloadData];
    }else {
        //1.2 缓存中没有数据,网络请求数据
        [self loadRightData:large.gc_id];
    }
    
    //2.刷新左侧的视图
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (GYlargeCategory *model in self.leftLarges) {
            if ([large.gc_id isEqualToString:model.gc_id]) {
                model.select = YES;
            }else {
                model.select = NO;
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [tableView reloadData];            
        });
    });
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier];
    
    return [cell getHeight:self.leftLarges[indexPath.row]];
}



#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.rightSources.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //1.首先取得模型数据
    GYLife *life = self.rightSources[section];
    return life.child.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GYRightCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:rightCellIdentifier forIndexPath:indexPath];
    GYLife *sectionLife = self.rightSources[indexPath.section];
    GYLife *life = sectionLife.child[indexPath.item];
    cell.titileLable.text = life.gc_name;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //拿到点击的那个item
    GYLife *sectionLife = self.rightSources[indexPath.section];
    GYLife *life = sectionLife.child[indexPath.item];
    
    //跳转到搜索界面
    GYSearchResultViewController *searchResultVC = [[GYSearchResultViewController alloc] initWithNibName:@"GYSearchResultViewController" bundle:nil];
    searchResultVC.gc_id = life.gc_id;
    [self.navigationController pushViewController:searchResultVC animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        GYRightHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:rightHeadIdentifier forIndexPath:indexPath];
        GYLife *sectionLife = self.rightSources[indexPath.section];
        headView.titleLable.text = sectionLife.gc_name;
        headView.markLable.backgroundColor = self.colors[indexPath.section];
        
        return headView;
    }
    return nil;
}

//设置每个分区内容的显示区域 4边边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 10, 5, 10);
}


#pragma mark -- UISearchBar 

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    GYSearchViewController *searchVC = [[GYSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    
    [searchBar resignFirstResponder];
}


#pragma mark -- 懒加载

- (NSArray *)colors {
    if (!_colors) {
        _colors = @[RGBColor(39, 205, 193),RGBColor(172, 148, 235),RGBColor(85, 193, 230),RGBColor(161, 211, 109),RGBColor(79, 206, 174),RGBColor(234, 137, 190),RGBColor(254, 205, 95),RGBColor(96, 158, 233),RGBColor(249, 110, 87)];
    }
    return _colors;
}

- (NSMutableDictionary *)cachesRightSources {
    if (!_cachesRightSources) {
        _cachesRightSources = [NSMutableDictionary dictionary];
    }
    return _cachesRightSources;
}

@end
